/*
 * @Author: 姚潘涛
 * @Date: 2024-04-08 15:18:03
 * @LastEditors: 姚潘涛
 * @LastEditTime: 2024-10-10 15:11:59
 * @Description:
 *
 * Copyright (c) 2024 by pandaman, All Rights Reserved.
 */
#include "xict_cpp/core/stage/heartbeat_sender.h"

namespace xict_cpp {
    namespace core {
        namespace stage {
            bool HeartbeatSenderStage::Init() {
                HeartbeatSenderStageParams params;
                return Init(params);
            }

            bool HeartbeatSenderStage::Init(
                const HeartbeatSenderStageParams& params) {
                params_ = params;
                return Initialize();
            }

            bool HeartbeatSenderStage::Process() {
                if (!mtx_.try_lock_for(std::chrono::milliseconds(
                        int(1000 / params_.frequency)))) {
                    if (params_.enable) {
                        SendHeartBeat();
                    }
                }
                return true;
            }

            void HeartbeatSenderStage::SendHeartBeat() {
                heart_beat_sock_ptr_->Send(params_.cmd_heartbeat);
                if (params_.is_log) {
                    ADEBUG_F("Send cmd: {}", params_.cmd_heartbeat.c_str());
                }
            }

            bool HeartbeatSenderStage::Initialize() {
                heart_beat_sock_ptr_ = std::make_shared<bridge::UdpSocket>(
                    io_service_, params_.ip, params_.port);
                return true;
            }

            void HeartbeatSenderStage::Reset() {
                if (heart_beat_sock_ptr_) {
                    heart_beat_sock_ptr_.reset();
                    heart_beat_sock_ptr_ = nullptr;
                }
            }
        }   // namespace stage
    }       // namespace core
}   // namespace xict_cpp